// pages/order/order.js
const app = getApp();
const request = require('../../utils/request');

Page({
  data: {
    orders: [],
    loading: true,
    currentTab: 0,
    statusList: ['全部', '待支付', '已支付', '已取消']
  },

  onLoad() {
    this.loadOrders();
  },

  onShow() {
    // 从其他页面返回时刷新订单
    // V1.0.1: 检查登录状态和游客状态
    const userInfo = wx.getStorageSync('userInfo');
    if (userInfo && userInfo.id && !userInfo.isGuest) {
      this.loadOrders();
    } else if (userInfo && userInfo.isGuest) {
      // 如果是游客，提示去登录
      wx.showModal({
        title: '提示',
        content: '游客不能查看订单，请先登录账号或注册账号',
        confirmText: '去登录',
        success: (res) => {
          if (res.confirm) {
            wx.navigateTo({
              url: '/pages/login/login'
            });
          } else {
            wx.navigateBack();
          }
        }
      });
    }
  },

  // 加载订单列表
  async loadOrders() {
    // V1.0.1 更新：使用userId而不是openid
    const userInfo = wx.getStorageSync('userInfo') || app.globalData.userInfo;
    const token = wx.getStorageSync('token');
    
    if (!token || !userInfo || !userInfo.id) {
      wx.showModal({
        title: '提示',
        content: '请先登录查看订单',
        confirmText: '去登录',
        success: (res) => {
          if (res.confirm) {
            wx.navigateTo({
              url: '/pages/login/login'
            });
          }
        }
      });
      this.setData({ loading: false });
      return;
    }

    // 检查是否是游客（游客不能查看订单）
    if (userInfo.isGuest === true || userInfo.isGuest === 1) {
      wx.showModal({
        title: '提示',
        content: '游客不能查看订单，请先登录账号或注册账号',
        confirmText: '去登录',
        success: (res) => {
          if (res.confirm) {
            wx.navigateTo({
              url: '/pages/login/login'
            });
          } else {
            // 用户取消，返回上一页
            wx.navigateBack();
          }
        }
      });
      this.setData({ loading: false });
      return;
    }

    try {
      let status = undefined;
      if (this.data.currentTab > 0) {
        status = this.data.currentTab - 1;
      }

      const res = await request.get('/orders', {
        status
      });

      if (res.success) {
        const orders = res.data.list || res.data;
        
        // 解析每个订单的规格信息
        orders.forEach(order => {
          if (order.spec_info) {
            try {
              order.specInfoParsed = JSON.parse(order.spec_info);
            } catch (e) {
              order.specInfoParsed = null;
            }
          }
        });
        
        this.setData({
          orders: orders,
          loading: false
        });
      } else {
        wx.showToast({
          title: res.message || '加载失败',
          icon: 'none'
        });
        this.setData({ loading: false });
      }
    } catch (error) {
      console.error('加载订单失败:', error);
      wx.showToast({
        title: '网络错误',
        icon: 'none'
      });
      this.setData({ loading: false });
    }
  },

  // 切换标签
  switchTab(e) {
    const index = e.currentTarget.dataset.index;
    this.setData({
      currentTab: index,
      loading: true
    });
    this.loadOrders();
  },

  // 查看订单详情
  viewDetail(e) {
    const orderNo = e.currentTarget.dataset.orderno;
    wx.navigateTo({
      url: `/pages/order-detail/order-detail?orderNo=${orderNo}`
    });
  },

  // 取消订单
  async cancelOrder(e) {
    const orderNo = e.currentTarget.dataset.orderno;

    const confirmRes = await wx.showModal({
      title: '提示',
      content: '确定要取消该订单吗？'
    });

    if (!confirmRes.confirm) {
      return;
    }

    wx.showLoading({ title: '取消中...' });

    try {
      const res = await request.put(`/orders/${orderNo}/cancel`);
      wx.hideLoading();

      if (res.success) {
        wx.showToast({
          title: '已取消',
          icon: 'success'
        });
        this.loadOrders();
      } else {
        wx.showToast({
          title: res.message || '取消失败',
          icon: 'none'
        });
      }
    } catch (error) {
      wx.hideLoading();
      console.error('取消订单失败:', error);
      wx.showToast({
        title: '网络错误',
        icon: 'none'
      });
    }
  },

  // 继续支付
  async continuePay(e) {
    const orderNo = e.currentTarget.dataset.orderno;

    wx.showToast({
      title: '功能开发中',
      icon: 'none'
    });
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.loadOrders().then(() => {
      wx.stopPullDownRefresh();
    });
  }
});


